package cn.cxy.albumselecttoolkit_demo

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import cn.cxy.albumselecttoolkit.AlbumSelectActivity
import cn.cxy.albumselecttoolkit.AlbumSelectConstants.EXTRA_CONFIG
import cn.cxy.albumselecttoolkit.AlbumSelectConstants.EXTRA_SELECTED_FILE
import cn.cxy.albumselecttoolkit.CropConfig
import cn.cxy.albumselecttoolkit.SelectImageConfig
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private val SELECT_IMAGE_REQUEST_CODE = 0x0000001
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener { applyPermissionAndSelectImage() }
    }

    private fun applyPermissionAndSelectImage() {
        val intent = Intent(this, AlbumSelectActivity::class.java)
        val cropConfig = CropConfig(10, 10, 600, 600)
        val selectImageConfig = SelectImageConfig(1, true, cropConfig)
        intent.putExtra(EXTRA_CONFIG, selectImageConfig)
        startActivityForResult(intent, SELECT_IMAGE_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SELECT_IMAGE_REQUEST_CODE && data != null) {
            val imageUri = data.getParcelableExtra<Uri>(EXTRA_SELECTED_FILE)
            imageUri?.let { showImage(it) }
        }
    }

    private fun showImage(file: Uri) {
        Glide.with(this)
            .load(file)
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(imageView)
    }

}